package com.vhuomai.product.service.impl;

import com.quanyue.auto.util.AssertUtils;
import com.vhuomai.product.entity.BaseProductCategory;
import com.vhuomai.product.mapper.ProductCategoryMapper;
import com.vhuomai.product.service.ProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author harris
 */
@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {

    @Autowired
    private ProductCategoryMapper categoryMapper;

    @Override
    public List<BaseProductCategory> findByParentId(int parentId) {
        return categoryMapper.findByParentId(parentId);
    }

    @Override
    public BaseProductCategory add(BaseProductCategory category) {
        BaseProductCategory productCategory = categoryMapper.findByNameParentId(category.getName());
        AssertUtils.isNull(productCategory, "不允许重复添加");
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(category.getCreateTime());
        categoryMapper.insert(category);
        return category;
    }

    @Override
    public void update(BaseProductCategory category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateSelective(category);
    }

    @Override
    public void remove(int id) {
        int count = categoryMapper.findChildrenCount(id);
        AssertUtils.isTrue(count == 0, "请先删除子类型");
        categoryMapper.deleteOne(id);
    }
}
